package com.vilen.weixin.quartz;

import com.vilen.weixin.json.AccessToken;
import com.vilen.weixin.json.ErrorEntity;
import com.vilen.weixin.model.WeixinContext;
import com.vilen.weixin.model.WeixinFinalValue;
import com.vilen.weixin.util.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by Administrator on 2016/2/9.
 */
@Component
public class RefreshAccessTokenTask  {
    public void refreshToken() {
        //WeixinContext.setAccessToken(WeixinFinalValue.TEMP_AT);

        HttpGet get = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClients.createDefault();
            String url = WeixinFinalValue.ACCESS_TOKEN_URL;
            url = url.replaceAll("APPID",WeixinFinalValue.APPID);
            url = url.replaceAll("APPSECRET",WeixinFinalValue.APPSECRET);
            System.out.println(url);
            get = new HttpGet(url);
            response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if(statusCode>=200&&statusCode<300) {
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity);
                System.out.println(content);
                try {
                    AccessToken at = (AccessToken) JsonUtil.getInstance().json2obj(content,AccessToken.class);
                    System.out.println(at.getAccess_token()+","+at.getExpires_in());
                    WeixinContext.setAccessToken(at.getAccess_token());
                } catch (Exception e) {
                    ErrorEntity err = (ErrorEntity)JsonUtil.getInstance().json2obj(content,ErrorEntity.class);
                    System.out.println("获取token异常:"+err.getErrcode()+","+err.getErrmsg());
                    refreshToken();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(response!=null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(client!=null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
